#include "HelloWorldScene.h"
#include "Constants.h"
#include "GameState.h"
#include "CGameManager.h"
#include "CBird.h"
#include "Utils.h"
USING_NS_CC;

CCScene* HelloWorld::scene() {
	CCScene *scene = CCScene::create();

	HelloWorld *layer = HelloWorld::create();

	scene->addChild(layer, indexGameLayer);

	return scene;
}

bool HelloWorld::init() {

	if (!CCLayer::init()) {
		return false;
	}
	if (currentLayer == kGameOverLayer) {
		this->removeChild(gameOverLayer);
		currentLayer = kGameLayer;
	}
	nestsArray = new CCArray();

	visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	start = visibleSize.height / 7;
	delta = (visibleSize.height) / 4;
	GameState::getInstance()->init(this);

	middle = ccp(visibleSize.width / 2, visibleSize.height / 2);

	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	CCSprite* backGroundSprite = CCSprite::create(BACKGROUND_IMAGE);

	backGroundSprite->setPosition(ccp(visibleSize.width / 2 + origin.x,
			visibleSize.height / 2 + origin.y));

	this->addChild(backGroundSprite, 0);

	_egg = CEgg::CreateEggBYFileName(EGG_IMAGE);

	createNests();
	startNests();

	birds = CBird::createBird();
	birds->setPosition(ccp(0, 0));
	this->addChild(birds, indexBird);

	birds->initBird();

	this->schedule(schedule_selector(HelloWorld::updateGame));

	this->setTouchEnabled(true);
	this->setKeypadEnabled(false);

	shot = false;

	return true;
}

void HelloWorld::updateGame(float dt) {

	GameState* gameState = GameState::getInstance();

	if (_egg->getState() == eggStateMoving
			&& _egg->boundingBox().containsPoint(
					ccp(birds->getXpos(), birds->getYpos()))) {
						CGameManager::Instance()->playSound(EGG_HIT);
						birds->gotShot();
						birds->setSpeedY(_egg->getYSpeed());
						_egg->setSpeedX(100);
						birds->setSpeedX(-100);
						shot = true;
					}

	if (_egg->getPositionY() < 0) {

		gameState->decreaseLifes();
		CGameManager::Instance()->playSound(JUMP_FAIL);
		if (gameState->getlifes() <= 0) {
			if (gameState->isBestScore()) {
				gameState->saveBestScore();
				CCUserDefault *def = CCUserDefault::sharedUserDefault();
				def->setBoolForKey(kNewBestScore, true);
				def->flush();
			} else {
				CCUserDefault *def = CCUserDefault::sharedUserDefault();
				def->setBoolForKey(kNewBestScore, false);
				def->flush();
			}
			gameOverLayer = CGameOverLayer::create();
			this->addChild(gameOverLayer, indexGameOverLayer);
			this->setKeypadEnabled(true);
			this->setTouchEnabled(false);
			currentLayer = kGameOverLayer;
		}
		_egg->reset();
		_egg->setRotation(0);

	} else {
		_egg->updateRobin(dt);
		if (_egg->getYSpeed() < 0) {

			CCObject* it;
			CCARRAY_FOREACH(nestsArray, it) {
				Nests *nest = static_cast<Nests*>(it);

				if (_egg->getBindable()
						&& nest->boundingBox().containsPoint(
								_egg->getPosition())) {
					if (_egg->getBindingNest()->getPositionY()
							< nest->getPositionY()) {
						_egg->bindtoNests(nest);
						if (shot){
							showbonus();
							GameState::getInstance()->increaseScores(5);
							shot = false;
						}else{
							GameState::getInstance()->increaseScores();
						}

						CGameManager::Instance()->playSound(JUMP_DONE);
						if (nest->getPositionY() > visibleSize.height / 2) {
							addNetst(start + 5 * delta);
							addNetst(start + 6 * delta);
							moveallNest();
						}
					}
				}
			}
		}
	}

	birds->update(dt);
}


void HelloWorld::showbonus(){
	CCSprite* bonus = CCSprite::create("bonus.png");
	bonus->setPosition(middle);
	this->addChild(bonus);
	CCAction* ac = CCFadeOut::create(1.0f);
	bonus->runAction(ac);
}

void HelloWorld::moveallNest() {

	check = true;
	_egg->setNetstMoving(true);
	CCObject* it;
	CCARRAY_FOREACH(nestsArray, it) {
		Nests *nest = static_cast<Nests*>(it);
		nest->stopAllActions();
	}
	CCARRAY_FOREACH(nestsArray, it) {
		Nests *nest = static_cast<Nests*>(it);
		CCPoint dest = ccp(nest->getPositionX(),
				nest->getPositionY() - 2*delta);
		CCMoveTo *move = CCMoveTo::create(1, dest);
		if (nestsArray->lastObject() == nest) {
			CCCallFuncN *funcdone = CCCallFuncN::create(this,
					callfuncN_selector(HelloWorld::moveallNestDone));
			nest->runAction(CCSequence::create(move, funcdone, NULL));
		} else
			nest->runAction(move);
	}

}

void HelloWorld::moveallNestDone() {
	CCObject* it;
	CCARRAY_FOREACH(nestsArray, it) {
		Nests *nest = static_cast<Nests*>(it);
		nest->movedown(2*delta);
		nest->Start();
	}

	CCARRAY_FOREACH(nestsArray, it) {
		Nests *nest = static_cast<Nests*>(it);
		if (nest->getPositionY() < 0) {
			nestsArray->removeObject(nest);
			this->removeChild(nest);
		}
	}
	_egg->setNetstMoving(false);
}

void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {
	CCSetIterator i;
	CCTouch *touch;
	CCPoint tap;
	if (_egg->getState()==eggStateFlying)
	CGameManager::Instance()->playSound(JUMP_SOUND);
	for (i = pTouches->begin(); i != pTouches->end(); i++) {
		touch = (CCTouch*) (*i);
		if (touch) {
			tap = touch->getLocation();
			CCLog("Touched: %f %f", tap.x, tap.y);
			if (_egg->getState() != eggStateMoving) {
				_egg->setZOrder(50);
				_egg->setState(eggStateMoving);

			}
		}
	}
}

void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {
	CCLog("ccTouchesMoved");
}

void HelloWorld::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {
	CCLog("ccTouchesEnded");
}

void HelloWorld::createNests() {
	addNetst(start);
	addNetst(start + delta);
	addNetst(start + 2 * delta);
	addNetst(start + 3 * delta);
	addNetst(start + 4 * delta);

	Nests *ne = static_cast<Nests*>(nestsArray->objectAtIndex(0));

	_egg->setPositionX(ne->getPositionX());
	_egg->setPositionY(ne->getPositionY() + ne->getContentSize().height / 2);

	_egg->bindtoNests(ne);
	this->addChild(_egg, indexEgg);
}

void HelloWorld::startNests() {
	CCObject* it;

	CCARRAY_FOREACH(nestsArray, it) {
		Nests *nest = static_cast<Nests*>(it);
		nest->Start();
	}
}
void HelloWorld::stopNests() {
	CCObject* it;

	CCARRAY_FOREACH(nestsArray, it) {
		Nests *nest = static_cast<Nests*>(it);
		nest->stopAllActions();
	}
}

void HelloWorld::addNetst(float y) {

	Nests* nests = Nests::CreateNestByFileName(NESTS_IMAGE);
	nests->setBehindNest((Nests*)nestsArray->lastObject());
	nests->setposition(y);
	this->addChild(nests, indexNets);
	nestsArray->addObject(nests);

}

//CCSprite* HelloWorld::initSoundButton(int state) {
//	if (state == SOUND_ON) {
//		CCSprite* soundOn = CCSprite::create(SOUND_ON_IMAGE);
//		return soundOn;
//	} else if (state == SOUND_OFF) {
//		CCSprite* soundOff = CCSprite::create(SOUND_OFF_IMAGE);
//		return soundOff;
//	}
//}
//
//void HelloWorld::soundEffectControl(CCObject* pSender) {
//
//	CCLog("soundEffectControl");
//
//	CCMenuItemImage* pMenuItem = (CCMenuItemImage*) pSender;
//
//	int state = CGameManager::Instance()->getSoundState();
//
//	pMenuItem->setNormalImage(initSoundButton(1 - state));
//
//	CGameManager::Instance()->changeSoundState(state);
//}

void HelloWorld::keyBackClicked(void) {
	programExit(NULL);
}

void HelloWorld::programExit(CCObject* pSender) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
	CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	exit(0);
#endif
#endif
}

